#!/usr/bin/env php
<?php
/**
 * Created by PhpStorm.
 * User: Inhere
 * Date: 2017/3/23 0023
 * Time: 23:52
 * RUN  `server/ws_server`
 */

require __DIR__ . '/../../../autoload.php';

use inhere\webSocket\server\App;
use inhere\webSocket\http\Request;
use inhere\webSocket\server\handlers\IRouteHandler;

define('PROJECT_PATH', __DIR__);

$options = [
    'debug' => true,
    'driver' => '',
];
$app = new App('', 9501, $options);

$app->onOpen(function (App $app, Request $request, int $id) {
    $app->respond([
        'total' => $app->getWs()->count()
    ], 'welcome!');
});

$app->onClose(function (App $app, int $id, array $client) {
    $app->respond([
        'total' => $app->getWs()->count()
    ]);
});

$rootHandler = $app->route('/', new \inhere\webSocket\server\handlers\RootHandler());

// commands
$rootHandler->add('test', function ($data, $index, IRouteHandler $handler) {

    return 'hello';
});

// if use `$app->jsonDataParser()` client send: {"cmd":"login","name":"john","pwd":123456}
// if use `$app->complexDataParser()` client send: [@login]{"name":"john","pwd":123456}
$rootHandler->add('login', function ($data, $cid, IRouteHandler $handler) {

    $name = $data['name'] ?? 'Please input your name.';

    $handler->respond("hello, $name. you login success, welcome!", '', 0, false)
        ->to($cid)
        ->send();

    // 1. will return text
    // return "hello, $name";

    // 2. will return formatted json
    // return $app->fmtJson("hello, $name");

    // 3. will return data type by `Application::isJsonType()`.
    // `Application::isJsonType() === true`  return formatted json.
    // `Application::isJsonType() === false` return raw text.
    // **it is recommended**
    $handler->respond("welcome new friend: $name join us.");
});

$rootHandler->add('logout', function ($data, $id, App $app) {
    $user = $app->getUser($id);

    return $app->respond("goodbye, {$user['name']}");
});

// start
$app->run();
